package com.minimalist.basic.config.request;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONWriter;
import com.minimalist.basic.utils.Sm4Util;
import lombok.extern.slf4j.Slf4j;
import org.jetbrains.annotations.NotNull;
import org.springframework.core.MethodParameter;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

import java.util.Set;

/**
 * @author 11987
 */
@RestControllerAdvice
@Slf4j
public class EncryptResponseBodyAdvice implements ResponseBodyAdvice<Object> {

    private final Set<String> excludePaths = Set.of("actuator", "api-docs", "druid", "myDruid");

    @Override
    public boolean supports(@NotNull MethodParameter returnType
            , @NotNull Class<? extends HttpMessageConverter<?>> converterType) {
        return true;
    }

    @Override
    public Object beforeBodyWrite(Object body, @NotNull MethodParameter returnType
            , @NotNull MediaType selectedContentType
            , @NotNull Class<? extends HttpMessageConverter<?>> selectedConverterType
            , @NotNull ServerHttpRequest request, @NotNull ServerHttpResponse response) {
        // 检查请求路径是否在排除列表中

        if (isExcludedPath(request.getURI().toString())) {
            return body;
        }

        // 检查请求头是否为 "Knife4j"
        if ("Knife4j".equals(request.getHeaders().getFirst("request-origion"))) {
            return body;
        }

        // 处理需要加密的响应体
        if (body != null) {
            String jsonString = body instanceof String ? (String) body : convertToJsonString(body);
            return Sm4Util.encrypt(jsonString);
        }
        ResponseEntity responseEntity = new ResponseEntity(response.getHeaders(), HttpStatus.OK);
        // 如果响应体为空，返回一个空的加密响应
        return Sm4Util.encrypt(convertToJsonString(responseEntity));
    }

    private boolean isExcludedPath(String uri) {
        for (String path : excludePaths) {
            if (uri.contains(path)) {
                return true;
            }
        }
        return false;
    }

    private String convertToJsonString(Object body) {
        return JSON.toJSONString(body, JSONWriter.Feature.WriteMapNullValue, JSONWriter.Feature.WriteLongAsString);
    }
}
